package cn.linjianhui.api.client;

import cn.linjianhui.api.client.config.RpcClientConfig;
import cn.linjianhui.api.client.invoker.impl.HttpClientTokenAuthenticator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Proxy;

@Component
public class ProxyFactory {

    private final RpcClientConfig config;

    @Autowired
    public ProxyFactory(RpcClientConfig config) {
        this.config = config;
    }

    public <T> T Create(Class<T> service, String client){
        String userToken = TokenManager.getTokenByCache(config.getUserName(),
                config.getUserPass(), config.getBaseAddress());

        String appToken = TokenManager.getAppTokenByCache(config.getAppKey(),
                config.getAppSecret(), config.getBaseAddress());

        HttpClientTokenAuthenticator authenticator = new HttpClientTokenAuthenticator(
                config.getUserName(), userToken, config.getAppKey(), appToken, client);

        RemoteServiceProxy handler = new RemoteServiceProxy(authenticator, service, config);
        Object proxy = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[] {service}, handler);

        return service.cast(proxy);
    }
}
